<template>
  <div>
    <el-container>
      <el-header class="inside-header">
        <div>
          <el-breadcrumb separator=">">
            <el-breadcrumb-item>账号管理</el-breadcrumb-item>
            <el-breadcrumb-item class="breadcrumbColor">工厂列表</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
      </el-header>
      <el-main>
        <div class="inside-main-box">
          <el-row class="inside-main" style="height: 46px;">
            <el-col :span="6" style="margin-left: 20px;">
              <el-form-item label="工厂名称" size="small">
                <el-input v-model="formData.name" placeholder="请输入工厂名称" maxLength="10" clearable/>
              </el-form-item>
            </el-col>
            <el-col :span="10" style="margin-left: 20px;">
              <el-button size="small" icon="search" class="sele-but" @click="getTableData(formData.name)">查询</el-button>
              <el-button size="small" icon="plus" class="add-but" @click="modifyDetail()">新增</el-button>
            </el-col>
          </el-row>
        </div>
        <div style="height: 10px; display: flex; align-items: center;background:#f2f4f5;margin:0 -19.5px 0 -20px">
        </div>
        <div style="background: #fff;">
          <el-table :data="tableData.rows" style="width: 100%;" height="460">
            <el-table-column label="工厂名称" prop="factory_name" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column label="地址" prop="address" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column label="描述" prop="description" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column label="创建时间" prop="create_date" align="center" show-overflow-tooltip :formatter="function(row,column){
              if(row.create_date){
                return $moment(row.create_date).format('YYYY-MM-DD HH:mm:ss')
              }else{
                return ''
              }
            }"></el-table-column>
            <el-table-column label="更新时间" prop="update_date" align="center"  show-overflow-tooltip :formatter="function(row,column){
              if(row.update_date){
                return $moment(row.update_date).format('YYYY-MM-DD HH:mm:ss')
              }else{
                return ''
              }
            }"></el-table-column>
            <el-table-column label="操作" align="center" width="240">
              <template #default="item">
                  <el-button plain link type="primary" size="small" icon="edit" @click="modifyDetail(item)">修改</el-button>
                  <el-button size="small" type="danger" link plain icon="Delete" @click="handleDelete(item)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="paginationBox">
          <el-pagination style="margin-right:40px; display: flex; justify-content: flex-end"  v-model:currentPage="obj.currentPage" v-model:page-size="obj.pageSize"
           size="small" layout="prev, pager, next, jumper,total"
          :total="tableData.total || 0" @size-change="handleChangePage" @current-change="handleChangePage"/>
          </div>
        </div>
      </el-main>
    </el-container>
    <!-- 新增弹窗 -->
    <el-dialog v-model="centerDialogVisible" title="工厂管理" width="40%">
      <div style="width:90%">
        <el-form ref="ruleFormRef" :model="formData.form" status-icon :rules="rules" label-width="120px" class="demo-ruleForm">
          <el-form-item label="名称" prop="factory_name">
            <div>
              <el-input v-model="formData.form.factory_name" maxLength="10" placeholder="请输入" autocomplete="off" />
            </div>
            <div style="margin-left: 10px;">
              <span style="font-size: 2px;color: #888;">支持中文、英文、数字</span>
            </div>
          </el-form-item>
          <el-form-item label="联系电话" prop="tel">
              <el-input v-model="formData.form.tel" placeholder="请输入" autocomplete="off" />
          </el-form-item>
          <el-form-item label="地址" prop="address">
              <el-input v-model="formData.form.address" placeholder="请输入" maxLength="200" autocomplete="off" />
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input v-model="formData.form.description" type="textarea" maxLength="500" placeholder="请选择">
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
          <span class="dialog-footer">
              <el-button class="sele-but" @click="saveFactory(formData.form)">保存</el-button>
              <el-button class="empty-but" @click="revert()">取消</el-button>
          </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from "vue";
import {getFactoryInfo,addFactory,updateFactory,deleteFactory} from "@/api/factory"
import {ElLoading, ElMessage, ElMessageBox} from "element-plus";
let obj = reactive({
  currentPage: 1,
  pageSize: 10,
});
const validateTelephoneNumber =() =>{
  return (rule,value,callback)=>{
    if(!value){
      callback(new Error("手机号没填."))
    }else if(!/^1\d{10}$/.test(value)){
      callback(new Error("手机号码格式错误."))
    }else{
      callback();
    }
  }
}
const rules = {
  factory_name: [{required: true,message: "请输入工厂名",trigger: "blur"}],
  tel:[{required:true,validator:validateTelephoneNumber(),trigger:"blur"}]
};
let formData = reactive({
  name:"",
  form:{
    factory_name:"",
    address:"",
    tel:"",
    description:"",
  }
});
let centerDialogVisible = ref(false);
let configShow = ref(false);
let ruleFormRef = ref(false);

const handleChangePage = (e) => {
  obj = { ...obj, ...e };
  getTableData(null);
};

const modifyDetail = (item) => {
  if(item){
    formData.form = JSON.parse(JSON.stringify(item.row));
  }else{
    formData.form={
      factory_name:"",
      address:"",
      tel:"",
      description:"",
    };
  }
  centerDialogVisible.value = true;
};

const handleDelete = (item) =>{
  ElMessageBox.confirm("确定要删除吗?").then(()=>{
    let data = JSON.parse(JSON.stringify(item.row))
    deleteFactory(data)
        .then((res) => {
          if(res.code=="200"){
            ElMessage({
              message: "success",
              type: "success",
            });
            getTableData(null);
          }else{
            ElMessage({
              message: res.msg,
              type: "error",
            });
          }
        });
  });
}

const cancelOderDetail = () => {
  centerDialogVisible.value = false;
  configShow.value = false;
};

const saveFactory = (item)=>{
  ruleFormRef.value.validate(valid=>{
    if(valid){
      let loadingInstance = ElLoading.service({
        lock: true,
        text: "saving……",
        background: 'rgba(0, 0, 0, 0.1)'
      });
      if(item.id){
        updateFactory(item)
            .then((res) => {
              if(res.code=="200"){
                ElMessage({
                  message: "success",
                  type: "success",
                });
                loadingInstance.close();
                revert()
              }else{
                ElMessage({
                  message: res.msg,
                  type: "error",
                });
              }
            });
      }else{
        addFactory(item)
            .then((res) => {
            if(res.code=="200"){
              ElMessage({
                message: "success",
                type: "success",
              });
              loadingInstance.close();
              revert()
            }else{
              ElMessage({
                message: res.msg,
                type: "error",
              });
            }
          });
      }
    }
  })
};

const revert = () =>{
  formData.form={
    factory_name:"",
    address:"",
    tel:"",
    description:"",
  };
  getTableData();
  ruleFormRef.value.clearValidate();
  centerDialogVisible.value=false;
}
let tableData = reactive({
  rows: [
  ],
  total:0
});
const getTableData = (name) => {
  if(name){
    obj.currentPage = 1;
  }
  getFactoryInfo({
    factory_name:name,
    pageNum: obj.currentPage || 1,
    pageSize: obj.pageSize || 10,
  }).then((res) => {
    tableData.rows = res.data.list;
    tableData.total = res.data.total
  });
};
onMounted(() => {
  getTableData();
});
</script>

<style scoped>
/* 面包屑字体颜色更改 */
.breadcrumbColor>>>.el-breadcrumb__inner {
  color: #000;
}
/* 内部header */
.inside-header {
  height: 20px;
  display: flex;
  justify-content: left;
  align-items: flex-start;
  background:#f2f4f5
}
.paginationBox{
  padding:10px;
  display: flex;
  justify-content: flex-end;
}
/* 空心按钮样式 */
.empty-but {
  border: 1px solid #3780b9;
  color: #3780b9;
}
/* 实心按钮背景样式 */

.sele-but {
  background: #3780b9;
  border: 0;
  border-radius: 2px;
  color: white;
}

.add-but {
  background: #dde5fe;
  color: #3780b9;
}
/* 分页 */
.demo-pagination-block {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
</style>
